/**
 * Copyright 2014-2020  the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.upb.webserver.security;

import com.upb.webserver.account.AccountService;
import com.upb.webserver.common.enums.AccountStatusEnum;
import com.upb.webserver.common.enums.PlatformEnum;
import com.upb.webserver.common.exception.WebServerException;
import com.upb.webserver.common.pojo.account.AccountCommon;
import com.upb.webserver.common.returncode.ConstantCode;
import com.upb.webserver.common.tools.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * config account and role.
 */
@Slf4j
@Service
public class AccountDetailsService implements UserDetailsService {
    @Autowired
    private AccountService accountService;

    @Override
    public UserDetails loadUserByUsername(String accountJsonBase64) throws UsernameNotFoundException {
        log.debug("start exec method [loadUserByUsername]. accountJsonBase64:{}", accountJsonBase64);
        AccountCommon account = null;
        try {
            account = accountService.getAccountCommon(accountJsonBase64);
        }catch (WebServerException wex){
            log.warn("fail exec method [loadUserByUsername]： throw exception WebServerException", wex);
            throw new UsernameNotFoundException(JsonUtils.objToString(wex.getRetCode()));
        }catch (Exception ex) {
            log.warn("fail exec method [loadUserByUsername]： convert LoginAccount not success", ex);
            throw new UsernameNotFoundException(JsonUtils.objToString(ConstantCode.INVALID_ACCOUNT_NAME));
        }

        if (Objects.isNull(account)) {
            log.warn("not found account record by accountJsonBase64:{}", accountJsonBase64);
            throw new UsernameNotFoundException(JsonUtils.objToString(ConstantCode.INVALID_ACCOUNT_NAME));
        }

        //check status
        checkAccountStatus(account.getAccount(), account.getPlatform(), account.getStatus());
        List<GrantedAuthority> list = Arrays.asList(new SimpleGrantedAuthority("ROLE_" + account.getRoleName()));
        User authUser = new User(accountJsonBase64, account.getPassword(), list);
        log.debug("success exec method [loadUserByUsername]. result:{}", JsonUtils.objToString(authUser));
        return authUser;
    }


    private void checkAccountStatus(String account, byte platform, byte status) {
        log.info("start exec method [checkAccountStatus]. account:{} platform:{} status:{}", account, platform, status);
        if (PlatformEnum.DEVELOPER.getId() == platform && AccountStatusEnum.FREEZE.getId() == status) {
            log.warn("fail exec method [checkAccountStatus], current has bean frozen");
            throw new UsernameNotFoundException(JsonUtils.objToString(ConstantCode.USE_HAS_BEAN_FROZEN));
        }
        log.info("start exec method [checkAccountStatus]. account:{} platform:{} status:{}", account, platform, status);

    }
}
